<template>
    <div :class="selection"
      ref="reference"
      v-click-outside.capture="onClickOutside"
      v-click-outside:mousedown.capture="onClickOutside">
      <div :class="headerClass"
        @click="toggleMenu"
      >
        <!-- <input type="text" class="form-control input-sm"> -->
        <div :class="checkedListClass" v-if="multiple">
            <div :class="tagCheckedClass" v-for="(item,index) in values" :key="index" @click.stop="remote(item)">
              <span class="tag-text">{{item.value}}</span>
              <Icon type="ion-ios-close-empty" class="tag-icon" size="16"></Icon>
            </div>
        </div>
        <div class="select-selected-value" v-if="!multiple">
          <span>{{currentValue}}</span>
        </div>
        <div :class="selectIconCont">
          <div :class="selectArrow">
            <Icon :type="selectArrowIcon" ></Icon>
          </div>
          <div class="ifast-select-clear" @click.stop="clearBnt">
            <Icon type="ion-ios-close"></Icon>
          </div>
        </div>
        
      </div>
      <div :class="selectOpctionClass">
        <transition name="ifast-dropIn">
          <Drop  
          v-show="arrowChecked"
          :data-transfer="transfer"
          v-transfer-dom>
            <ul class="ifast-dropdown-list" v-show="arrowChecked">
                <functional-options
                  :options="selectOptions"
                  :slot-options="slotOptions"
                  :slot-update-hook="slotUpdateHook"
                ></functional-options>
            </ul>
          </Drop>
          <!-- <ul class="ifast-dropdown-list" v-show="arrowChecked">
            <li class="ifast-select-item ifast-select-checked" v-for="i in 5" :key="i">
                <span class="select-text"> {{i}}</span>
                <span class="float-right select-right">
                  <Icon type="ion-ios-checkmark-empty"></Icon>
                </span>
            </li>
            <slot></slot>
          </ul> -->
        </transition>
        
      </div>
    </div>
</template>

<script>
let prefixCls='ifast'
import Icon from '../icon/icon';
import Drop from'./dropdown';
import FunctionalOptions from'./functional-options'
import Emitter from '../../utils/emitter.js'
import TransferDom from '../../directives/transfer-dom.js'
import {directive as clickOutside} from 'v-click-outside-x';
import {findComponentDownward,oneOf } from'../../utils/index.js';

export default {
  name: 'iSelect',
  mixins:[Emitter],
  props:{
    size:{
      type:String,
       validator(val){
        return oneOf(val,['small','large'])
      }
    },
    selectArrowIcon:{
      type:String,
      default:'ion-ios-arrow-down'
    },
    multiple:{
      type:Boolean,
      default:false
    },
    value: {
        type: [String, Number, Array],
        default: ''
    },
    clear:{
      type:Boolean,
      default:false
    },
    disabled:{
      type:Boolean,
      default:false
    },
    transfer: {
      type: Boolean,
      default: false
    }
  },
  components:{Icon,Drop,FunctionalOptions},
  directives:{clickOutside,TransferDom},
  data(){
    return{
      arrowChecked:false,
      values:[],
      current:'',
      currentIndex:-1,
      currentValue:this.value,
      slotOptions:this.$slots.default
    }
  },
  computed:{
    selection(){
      return [
        `${prefixCls}-select-selection`,
        [{
          [`${prefixCls}-select-disabled`]:this.disabled,
          [`${prefixCls}-select-${this.size}`]:!!this.size,

        }]
      ]
    },
    headerClass(){
       return [
        `${prefixCls}-select-header`,
      ]
    },
    checkedListClass(){
       return [
        `${prefixCls}-checked-list`,
      ]
    },

    selectArrow(){
      return[
        `${prefixCls}-select-arrow`,
        [{
          [`${prefixCls}-select-arrow-checkd`]:this.arrowChecked,

        }]
      ]
    },
    selectIconCont(){
      return[
        `${prefixCls}-select-icon-cont`,
        [{
          [`${prefixCls}-select-icon-clear`]:this.clear && this.currentValue,

        }]
      ]
    },
    tagCheckedClass(){
      return [
        `${prefixCls}-tag-checked`,
      ]
    },
    selectOpctionClass(){
      return[
        `${prefixCls}-select-opction`,
      ]
    },
    selectOptions(){
      if(!this.multiple){
        this.values=[this.value];
      }
      let selectOptions = [];
      const slotOptions = (this.slotOptions || []);
      let currentIndex=-1;
      let optionCounter=this.currentIndex;
      //是否多选
      // if(this.multiple){

      // }else{
        for(let option of slotOptions){
          const cOptions = option.componentOptions;
          currentIndex=currentIndex+1;
          if (!cOptions) continue;
          selectOptions.push(this.processOpction(option, this.values, optionCounter === currentIndex));
        }
      // }
      return selectOptions
    }
  },
  methods: {
    remote(data){
       const valueIsSelected = this.values.find(({value}) => value === data.value);
        if (valueIsSelected){
            this.values = this.values.filter(({value}) => value !== data.value);
        } else {
            this.values = this.values.concat(data);
        }
        this.$emit('input',this.values);
    },
    //清除按钮
    clearBnt(){
       this.values=[];
       this.current='';
       this.currentValue=''
       this.$emit('input',this.current)
    },
    processOpction(option,values,isFocused){
       if (!option.componentOptions) return option;
        const optionValue = option.componentOptions.propsData.value;
        const disabled = option.componentOptions.propsData.disabled;
        let isSelected=false;
        if(this.multiple){
          isSelected = this.values.find(({value}) => value === optionValue);
          isSelected = typeof isSelected === 'undefined' ? false : true;
          // console.log('isSelected',isSelected)
        }else{
          isSelected = values.includes(optionValue);
        }
        
        const propsData = {
            ...option.componentOptions.propsData,
            selected: isSelected,
            isFocused: isFocused,
            disabled: typeof disabled === 'undefined' ? false : disabled !== false,
        };
        return {
            ...option,
            componentOptions: {
                ...option.componentOptions,
                propsData: propsData
            }
        };
    },
    isOverlap(attr,key){
    },
    slotUpdateHook(){
      this.slotOptions = this.$slots.default;
    },
    toggleMenu(event,force){
      if(this.disabled) return;
      this.arrowChecked=!this.arrowChecked;
      if(this.arrowChecked){
          this.broadcast('Drop', 'on-update-popper')
      }
    },
    onClickOutside(event){
      this.arrowChecked=false;
      // this.selectArrow
    },
    gatherOpction(){
      let newAttr=[]
      this.selectOptions.map((data,index)=>{
        newAttr.push(data);
      })
      return newAttr
    },
    colse(){
      this.toggleMenu(null,false);
    },
    opctionClick(data){
      this.current=String(data.label).trim();
      this.currentValue=this.current;
      let opctions=this.gatherOpction();
      //处理多选、单选
      if(this.multiple){
        const valueIsSelected = this.values.find(({value}) => value === data.value);
        if (valueIsSelected){
            this.values = this.values.filter(({value}) => value !== data.value);
        } else {
            this.values = this.values.concat(data);
        }
        this.$emit('input',this.values)
      }else{
        //查询属于第几个选项
        this.values=[this.current];
        this.colse();
        this.$emit('input',this.current);
      }
      this.currentIndex=opctions.findIndex((opt)=>{
        return opt.componentOptions.propsData.value === data.value;
      })
        
    }
  },
  mounted(){
    this.$on('on-select-selected',this.opctionClick)
  },
  watch: {
    selectOptions(){
      //重新计算 Drop
      this.broadcast('Drop', 'on-update-popper');
    },
  },
}
</script>

<style lang='scss' scoped>

</style>
